package com.jt.consumer.controller;

import com.jt.consumer.service.RemoteProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private RestTemplate restTemplate;
    //访问地址：http://localhost:8090/consumer/doRestEcho1
    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho01(){
        //1.定义要调用的远端服务的url
        String url="http://localhost:8081/provider/echo/"+appName;
        //2.基于restTemplate对象中的相关方法进行服务调用
        String s = restTemplate.getForObject(url, String.class);//没有负载均衡
        return s;
    }

    //访问地址：http://localhost:8090/consumer/doRestEcho2
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho02(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");//负载均衡
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
        return restTemplate.getForObject(url, String.class);
    }

    //访问地址：http://localhost:8090/consumer/doRestEcho3,将02代码简化
    @Autowired
    private RestTemplate loadBalancedRestTemplate;//注入时已经搭载了负载均衡
    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho03(){
        String url = "http://sca-provider/provider/echo/"+appName;//拦截器可以识别sca-provider
        return loadBalancedRestTemplate.getForObject(url, String.class);
    }

    //访问地址：http://localhost:8090/consumer/echo4
    @Autowired
    private RemoteProviderService remoteProviderService;
    @GetMapping("/consumer/echo4")
    public String doRestEcho04(){
        return remoteProviderService.echoMsg(appName);
    }


}
